package apps.softtech.fastmarket;


import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.ViewFlipper;
import apps.softtech.CustomView.SlideHolder;
import apps.softtech.Utility.ApplicationConstants;
import apps.softtech.Utility.ConnectionDetector;
import apps.softtech.Utility.HttpRequest;
import apps.softtech.fastmarket.adapter.AdapterPager;
import apps.softtech.fastmarket.adapter.AdapterCategoryList;
import apps.softtech.fastmarket.listenner.ListenerTabHost;
import apps.softtech.fastmarket.listenner.ListenerViewPager;
import apps.softtech.fastmarket.model.Category;
import apps.softtech.fastmarket.model.DatabaseHandler;
import apps.softtech.fastmarket.model.UserInfo;

public class ActivityDashboard extends FragmentActivity {

	private TabHost mTabHost;
    private ViewPager mViewPager;
    private AdapterPager mPagerAdapter;
    private ListenerTabHost listenerTabHost;
    private ListenerViewPager listenerViewPager;
	
    private SlideHolder mSlideHoder;
    
    private int mCurrentPage = 0;
    /**
     * data handler
     */
    DatabaseHandler dbh;
    /**
     * Context
     */
    Context mContext;
    /**
     * activity
     */
    Activity mActivity;
    
    /**
     * view flipper
     */
    ViewFlipper vfSlideHolder;
    /**
     * VIEW FLIPPER 1
     */
    ImageButton ibSlideCategory;
    RelativeLayout layoutSlideCatetory;
	/**
	 * VIEW FLIPPER 2
	 */
    Button btCategoryBack,btCategorOK,btCategoryChildBack,btCategoryChilOK;
   
    AdapterCategoryList mAdapterCategoryList;
   
    ListView lvCategory;
    ListView lvCategoryChild;
    ArrayList<Category> mCategoriesList = new ArrayList<Category>();
    Button btOpenSlide;
    Button btOpenSearch;
    
    ConnectionDetector cd = new ConnectionDetector(this);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_productlist);
		dbh = new DatabaseHandler(ActivityDashboard.this);
		//
		//get user id
		//
		SharedPreferences pref = ActivityDashboard.this.getSharedPreferences("market_data", 0);
		ApplicationConstants.MY_USER = pref.getInt(UserInfo.USERID, -1);
		// receive sms
		setId();
		// register gcm
		initRegisterGCM();
		
		init();
		initOnClick();
		
	}
	/**
	 * onclick Button
	 */
	private void initOnClick() {
		//
		//choose category
		//
		ibSlideCategory.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				getAllParentCategory();
				vfSlideHolder.setInAnimation(ActivityDashboard.this,R.anim.in_from_right);
				vfSlideHolder.showNext();
				
			}
		});
		layoutSlideCatetory.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				getAllParentCategory();
				vfSlideHolder.setInAnimation(ActivityDashboard.this,R.anim.in_from_right);
				vfSlideHolder.showNext();
			}
		});
	}

	/**
	 * get parent category
	 */
	private void getAllParentCategory() {
		if(cd.isConnectingToInternet()){
			dbh.deleteCategory(Category.CATEGORY_ID +  ">=0", null);
			new AsyncTaskGetParentCategolist().execute();
		}
		else{
		mCategoriesList = (ArrayList<Category>) dbh.getCategory(null, Category.PARENT_CATEGORY_ID
				+ " =?", new String[]{"0"}, null, null);
		if(mCategoriesList.size()!=0){
		setListCategoryParent();
		}
		}
		
	}
	/**
	 * set id for all views
	 */
	void setId(){
		mActivity = ActivityDashboard.this;
		mContext = ActivityDashboard.this;
		mSlideHoder = (SlideHolder) findViewById(R.id.container);
		mTabHost = (TabHost)findViewById(android.R.id.tabhost);
		this.mViewPager = (ViewPager)super.findViewById(R.id.viewpager);
		vfSlideHolder = (ViewFlipper)findViewById(R.id.vfSlideHolder);
		layoutSlideCatetory = (RelativeLayout) findViewById(R.id.layoutSlideCategory);
		//button 
		ibSlideCategory = (ImageButton) findViewById(R.id.ibSlideCategory);
		//Search
		initSearch();
		initFunctionSearch();
		// category
		initCategory();
		initFunctionCategory();
	}
	/**
	 * init search
	 */
	private void initSearch() {
		btOpenSlide = (Button)findViewById(R.id.btOpenSlide);
		btOpenSearch = (Button)findViewById(R.id.btOpenSearch);
	}
	/**
	 * init function search
	 */
	private void initFunctionSearch() {
		btOpenSlide.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mSlideHoder.open();
			}
		});
		btOpenSearch.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent inSearch = new Intent(ActivityDashboard.this,ActivitySearch.class);
				startActivity(inSearch);
			}
		});
	}
	/**
	 * init category list
	 */
	private void initCategory() {
		btCategoryBack = (Button) findViewById(R.id.btCategoryBack);
		btCategorOK = (Button)findViewById(R.id.btCategoryOK);
		btCategoryChildBack = (Button)findViewById(R.id.btCategoryChildBack);
		btCategoryChilOK = (Button) findViewById(R.id.btCategoryChildOK);
		//listview
		lvCategory = (ListView) findViewById(R.id.lvCategoryParent);
		lvCategoryChild =(ListView)findViewById(R.id.lvCategoryChild);
	}
	/**
	 * function
	 */
	private void initFunctionCategory() {
		btCategoryBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				vfSlideHolder.setInAnimation(ActivityDashboard.this,R.anim.in_from_left);
				vfSlideHolder.setDisplayedChild(0);
				
			}
		})	;
		btCategorOK.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// xu ly sau
				mTabHost.setCurrentTab(1);
				mViewPager.setCurrentItem(mTabHost.getCurrentTab());
				mSlideHoder.close();
			}
		});
		
		lvCategory.setOnItemClickListener( new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				int idCategory = mCategoriesList.get(position).getCategoryId();
				sendBroadCastCatoryParentId(idCategory);//
				mTabHost.setCurrentTab(1);
				mViewPager.setCurrentItem(mTabHost.getCurrentTab());
			}
		});
		btCategoryChildBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				vfSlideHolder.setInAnimation(ActivityDashboard.this,R.anim.in_from_left);
				vfSlideHolder.setDisplayedChild(1);
			}
		});
		btCategoryChilOK.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//xu ly sau
				mTabHost.setCurrentTab(1);
				mViewPager.setCurrentItem(mTabHost.getCurrentTab());
				mSlideHoder.close();
			}
		});
		lvCategoryChild.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				
			}
		});
	}
	
	/**
	 * send broadcast id catogery
	 */
	private void sendBroadCastCatoryParentId(int idCategory){
		Intent inSendIdCategory = new Intent(ApplicationConstants.RECEIVER_CATEGORY_ID_PARENT);
		inSendIdCategory.putExtra("st_CategoryId", idCategory);
		sendBroadcast(inSendIdCategory);
	}
	/**
	 * setup list category parent
	 */
	 private void setListCategoryParent(){
		mAdapterCategoryList = new AdapterCategoryList(mCategoriesList, mContext,vfSlideHolder,lvCategoryChild,mTabHost,mViewPager,mSlideHoder);
		lvCategory.setAdapter(mAdapterCategoryList);
			
	 }
	/**
	 * init variable's value when create activity
	 */
	void init(){
		initTabHost();
//		initChatOutApp();
		
	}
	/**
	 * init chat out app
	 */
	private void initChatOutApp() {
		//
		Intent inChat = new Intent(ActivityDashboard.this,ServiceShowChatHead.class);
		startService(inChat);
		
	}

	/**
	 * register gcm
	 */
	private void initRegisterGCM() {
		RegisterGoogleCM registerGcm = new RegisterGoogleCM(mActivity);
		registerGcm.registerGCM();
	}
	

	/**
	 * init tabhost
	 */
	void initTabHost(){
		mTabHost.setup();
        //init view page
        intialiseViewPager();
        //
        //listenner tab host
        //
        listenerTabHost = new ListenerTabHost(mTabHost, mViewPager, ActivityDashboard.this);
        listenerTabHost.createTab();
        listenerTabHost.setBackgroundTabSelect();
        mTabHost.setOnTabChangedListener(listenerTabHost);
        //
        //listener view page
        //
        listenerViewPager = new ListenerViewPager(mTabHost, mViewPager, ActivityDashboard.this);
        mViewPager.setOnPageChangeListener(listenerViewPager);
	}
	
	/**
	 * init viewpage and view page adapter
	 */
	private void intialiseViewPager() {
        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this, FragmentTabHome.class.getName()));
        fragments.add(Fragment.instantiate(this, FragmentTabCategory.class.getName()));
        fragments.add(Fragment.instantiate(this, FragmentTabNew.class.getName()));
//        fragments.add(Fragment.instantiate(this, FragmentTabHistory.class.getName()));
        fragments.add(Fragment.instantiate(this, FragmentTabNotification.class.getName()));
        this.mPagerAdapter  = new AdapterPager(super.getSupportFragmentManager(), fragments);
        
        ActivityDashboard.this.mViewPager.setAdapter(ActivityDashboard.this.mPagerAdapter);
    }
	
	/**
	 * set bitmap
	 */
	private Bitmap setBimap(){
		try{
		String url ="https://lh5.googleusercontent.com/-wocjYPvyASc/T3_mBi3-jrI/AAAAAAAAAEg/U7RYJu-I3N0/w385-h384-no/vemat9.jpg";
		Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
			     url).openConnection().getInputStream());
	return bitmap;
		}catch(Exception e){}
		return null;
	}
	/**
	 * get category parent
	 */
	private String requestGetParentCategoryList(){
		HttpRequest mHttpRequest = new HttpRequest();
		String url =ApplicationConstants.BASE_URL+"category/get_list_parent_category/";
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		
		JSONObject json = new JSONObject();
		try{
			json.put("st_GcmId", ApplicationConstants.RED_ID);
		}catch(Exception e){}
		params.add(new BasicNameValuePair("data", json.toString()));
		Log.v("",""+params);
		return mHttpRequest.makeServiceCall(url, HttpRequest.POST, params);
	}
	/**
	 * get category parent
	 *
	 */
	class AsyncTaskGetParentCategolist extends AsyncTask<Void, Void, Void>{

		ProgressDialog pd;
		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(mContext);
			pd.setMessage("Loading....");
			pd.show();
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... params) {
			try {
				JSONArray jsonData = new JSONArray();
				JSONObject jsonCategoryParentList = new JSONObject(requestGetParentCategoryList());
				int success = jsonCategoryParentList.getInt("success");
				if(success==1){
					jsonData = jsonCategoryParentList.getJSONArray("data");
					for(int i=0;i<jsonData.length();i++){
						JSONObject jsonList = new JSONObject(jsonData.getJSONObject(i).toString());
						dbh.insertCategory(new Category(jsonList.getInt("st_CategoryId"),
								jsonList.getString("st_CategoryName"), jsonList.getString("st_Description")
								, jsonList.getInt("st_ParentCategoryId"), jsonList.getInt("st_CategoryLevel")));
						mCategoriesList.add(new Category(jsonList.getInt("st_CategoryId"),
								jsonList.getString("st_CategoryName"), jsonList.getString("st_Description")
								, jsonList.getInt("st_ParentCategoryId"), jsonList.getInt("st_CategoryLevel")));
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			if(mCategoriesList.size()!=0){
				//firt load category
			sendBroadCastCatoryParentId(1);
			}
			setListCategoryParent();
			pd.dismiss();
			super.onPostExecute(result);
		}
		
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		dbh.close();
	}
}
